﻿using AutoMapper;
using MediatR;
using MyRabbit.Application.Command.SlaughteCommand;
using MyRabbit.Application.ErrorCode;
using MyRabbit.Domain;
using MyRabbit.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyRabbit.Application.CommandHandler.SlaughteCommandHandler
{
    public class SlaughteUpdateCommandHandler : IRequestHandler<SlaughteUpdateCommand, APIResult<object>>
    {
        /// <summary>
        /// 屠宰仓储
        /// </summary>
        private readonly IRepository<Slaughte> slaughteRep;
        /// <summary>
        /// 映射
        /// </summary>
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="slaughteRep"></param>
        /// <param name="mapper"></param>
        public SlaughteUpdateCommandHandler(IRepository<Slaughte> slaughteRep, IMapper mapper)
        {
            this.slaughteRep = slaughteRep;
            this.mapper = mapper;
        }
    
        public async Task<APIResult<object>> Handle(SlaughteUpdateCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Code=Codes.修改成功;
            result.Message=Codes.修改成功.ToString();
            try
            {
                Slaughte slaughte = new Slaughte();
                if (slaughte == null)
                {
                    throw new Exception("养殖信息不存在");
                }
                else
                {
                    slaughte.ProductionBatch = request.ProductionBatch;
                    slaughte.AverageWeight = request.AverageWeight;
                    slaughte.EntryTime = request.EntryTime;
                    slaughte.SlaughteTime = request.SlaughteTime;
                    await slaughteRep.UpdateAsync(slaughte);
                }
            }
            catch (Exception exp)
            {
                result.Code = Codes.修改失败;
                result.Message = Codes.修改失败.ToString()+exp.Message;

            }
            return await Task.FromResult(result);
        }
    }
}
